package com.luck.easyfoodbatch.ui;

import android.Manifest;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.drawable.BitmapDrawable;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.animation.FastOutSlowInInterpolator;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.luck.easyfoodbatch.App;
import com.luck.easyfoodbatch.Constant;
import com.luck.easyfoodbatch.R;
import com.luck.easyfoodbatch.adapter.ShopAdapter;
import com.luck.easyfoodbatch.adapter.ShopTypeAdapter;
import com.luck.easyfoodbatch.custom.RoundedImageView;
import com.luck.easyfoodbatch.glide.GlideCircleTransform;
import com.luck.easyfoodbatch.mvp.mine.CollectModel;
import com.luck.easyfoodbatch.mvp.mine.CollectPresenter;
import com.luck.easyfoodbatch.mvp.mine.CollectView;
import com.luck.easyfoodbatch.mvp.mine.GetClassesModel;
import com.luck.easyfoodbatch.mvp.mine.GetClassesPresenter;
import com.luck.easyfoodbatch.mvp.mine.GetClassesView;
import com.luck.easyfoodbatch.mvp.mine.ShopHomePageModel;
import com.luck.easyfoodbatch.mvp.mine.ShopHomePagePresenter;
import com.luck.easyfoodbatch.mvp.mine.ShopHomePageView;
import com.luck.easyfoodbatch.mvp.model.ClassM;
import com.luck.easyfoodbatch.mvp.model.Collect;
import com.luck.easyfoodbatch.mvp.model.SearchGoods;
import com.luck.easyfoodbatch.util.HttpUtil;
import com.luck.easyfoodbatch.util.SharedPreferencesUtil;
import com.luck.easyfoodbatch.util.T;
import com.luck.easyfoodbatch.util.ToolbarUtil;
import com.luck.easyfoodbatch.util.Tools;
import com.luck.easyfoodbatch.util.Utils;
import com.luck.easyfoodbatch.util.XLHRatingBar;
import com.luck.easyrecyclerview.EasyRecyclerView;
import com.luck.easyrecyclerview.adapter.RecyclerArrayAdapter;
import com.luck.easyrecyclerview.decoration.RecycleViewDivider;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class ShopHomeActivity extends BaseActivity implements RadioGroup.OnCheckedChangeListener, RecyclerArrayAdapter.OnLoadMoreListener, ShopHomePageView, CollectView, GetClassesView {

    @BindView(R.id.right_title)
    TextView rightTitle;
    @BindView(R.id.iv_icon)
    RoundedImageView ivIcon;
    @BindView(R.id.tv_shop_name)
    TextView tvShopName;
    @BindView(R.id.rb_tab1)
    RadioButton rbTab1;
    @BindView(R.id.rb_tab2)
    RadioButton rbTab2;
    @BindView(R.id.rb_tab3)
    RadioButton rbTab3;
    @BindView(R.id.rabs)
    RadioGroup rabs;
    @BindView(R.id.indicator)
    View indicator;
    @BindView(R.id.recyclerView)
    EasyRecyclerView recyclerView;
    @BindView(R.id.rl_follow)
    RelativeLayout rlFollow;
    @BindView(R.id.rl_shop)
    RelativeLayout rlShop;
    @BindView(R.id.btn_type)
    Button btnType;
    @BindView(R.id.btn_introduction)
    Button btnIntroduction;
    @BindView(R.id.btn_chat)
    Button btnChat;
    @BindView(R.id.rb_sort)
    RadioButton rbSort;
    @BindView(R.id.rb_volume)
    RadioButton rbVolume;
    @BindView(R.id.rb_day)
    RadioButton rbDay;
    @BindView(R.id.rb_price)
    RadioButton rbPrice;
    @BindView(R.id.rb_period)
    RadioButton rbPeriod;
    @BindView(R.id.rgbs)
    RadioGroup rgbs;
    @BindView(R.id.tv_line1)
    TextView tvLine1;
    @BindView(R.id.tv_line2)
    TextView tvLine2;
    @BindView(R.id.tv_tag)
    TextView tv_tag;
    @BindView(R.id.ratingBar3)
    XLHRatingBar ratingBar3;
    @BindView(R.id.tv_follow)
    TextView tv_follow;
    @BindView(R.id.ll_bottom)
    LinearLayout ll_bottom;
    @BindView(R.id.tv_is_coup)
    TextView tv_is_coup;
    private ShopAdapter adapter;
    private ShopHomePageModel pageModel;
    private List<SearchGoods.DataBean.ModelsBean> list = new ArrayList<>();
    private List<ClassM.DataBean> values = new ArrayList<>();
    private String shop_name = "", shop_avatar = "", shop_id = "", class_id = "", sort = "", goods_date = "", mobile = "";
    private int score = 0;
    private int totalPage = 1;
    private int page = 1;
    private int isRefresh = 0;
    private CollectModel collectModel;
    private int isCollect = 0;
    private SearchGoods.DataBean.ShopBean shop;
    private SearchGoods.DataBean data;
    private boolean day = false;
    private boolean price = false;
    private int existVoucher = 0;
    private String vids = "";
    private GetClassesModel classesModel;
    private String toChatUsername = "", p_id = "";
    private BroadcastReceiver registerReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals("action.app.refresh.shop")) {
                if (pageModel == null) {
                    pageModel = new ShopHomePagePresenter(ShopHomeActivity.this, mContext);
                }
                pageModel.homePageList(shop_id, class_id, sort, goods_date, p_id);
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_shop_home, "店铺主页", MODE_BACK_NAVIGATION);
        App.getInstance().addActivity(ShopHomeActivity.this);
        ButterKnife.bind(this);
        p_id = (String) SharedPreferencesUtil.getData(ShopHomeActivity.this, HttpUtil.P_ID, "3");
        registerReceiver(registerReceiver, "action.app.refresh.shop");
        final int type = getIntent().getIntExtra("type", 0);
        shop_id = getIntent().getStringExtra("shop_id");
        toChatUsername = getIntent().getStringExtra("toChatUsername");
        //class_id = getIntent().getStringExtra("class_id");
        class_id = "";
        pageModel = new ShopHomePagePresenter(this, mContext);
        showProgressDialog(getString(R.string.app_loading));
        pageModel.homePageList(shop_id, class_id, sort, goods_date, p_id);
        classesModel = new GetClassesPresenter(this, mContext);
        classesModel.requestShopClass(shop_id);
        //Tools.modifyTextViewDrawable(this, rightTitle, R.mipmap.share_1x, 0);
        rabs.setOnCheckedChangeListener(this);

        rabs.post(new Runnable() {
            @Override
            public void run() {
                if (type == 1) {
                    // 指定全部商品
                    sort = "";
                    rbTab2.setChecked(true);
                    initCheckedTab(rbTab2);
                } else {
                    sort = "1";
                    initCheckedTab(rbTab1);
                }
            }
        });
        LinearLayoutManager manager = new LinearLayoutManager(mContext);
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        recyclerView.addItemDecoration(new RecycleViewDivider(
                mContext, LinearLayoutManager.HORIZONTAL, Utils.dip2px(mContext, 0.5F), getResources().getColor(R.color.line_color)));
        recyclerView.setLayoutManager(manager);
        adapter = new ShopAdapter(mContext);
        adapter.addAll(list);
        recyclerView.setAdapter(adapter);
        adapter.setMore(R.layout.view_more, this);
        adapter.setNoMore(R.layout.view_nomore);

        adapter.setOnItemClickListener(new RecyclerArrayAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(int position, View v) {
                SearchGoods.DataBean.ModelsBean bean = list.get(position);
                Bundle bundle = new Bundle();
                bundle.putString("gid", bean.getGid() + "");
                startAct(ShopDetailsActivity.class, bundle);
            }
        });
        adapter.setError(R.layout.view_error).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                adapter.resumeMore();
            }
        });


    }

    private boolean isChecked = false;

    @OnClick({R.id.rb_sort, R.id.rb_volume, R.id.tv_is_coup, R.id.tv_follow, R.id.rb_day, R.id.rb_price, R.id.rb_period, R.id.right_title, R.id.btn_chat, R.id.btn_introduction, R.id.btn_type})
    public void onClick(View v) {
        Intent intent = new Intent();
        Bundle bundle = new Bundle();
        switch (v.getId()) {
            case R.id.right_title:
                //T.showToast(mContext, "分享");
                break;
            case R.id.btn_chat:
                if (Onrecord()) {
                    if (isCheckedLogin()) {
                        bundle.putString(Constant.EXTRA_USER_ID, toChatUsername);
                        bundle.putString(Constant.EXTRA_NICK_ID, shop_name);
                        startAct(ChatActivity.class, bundle);
                    } else {
                        startAct(LoginActivity.class);
                    }
                }
                break;
            case R.id.btn_introduction:
                if (data != null) {
                    bundle.putInt("is_collect", data.getIs_collect());
                    bundle.putSerializable("shop", data.getShop());
                    bundle.putString("shop_id", shop_id);
                    bundle.putString(Constant.EXTRA_USER_ID, toChatUsername);
                    bundle.putString(Constant.EXTRA_NICK_ID, shop_name);
                    startAct(ShopIntroductionActivity.class, bundle);
                }
                break;
            case R.id.btn_type:
                new PopupWindows(mContext, ll_bottom);
                break;
            case R.id.rb_sort:
                // 综合
                if (!isFastDoubleClick()) {
                    sort = "2";
                    isRefresh = 0;
                    page = 1;
                    pageModel.homePageList(shop_id, class_id, sort, goods_date, p_id);
                }
                break;
            case R.id.rb_volume:
                // 按销量
                if (!isFastDoubleClick()) {
                    sort = "3";
                    isRefresh = 0;
                    page = 1;
                    pageModel.homePageList(shop_id, class_id, sort, goods_date, p_id);
                }
                break;
            case R.id.rb_day:
                //按日期
                if (!isFastDoubleClick()) {
                    if (!day) {
                        sort = "4";
                        Tools.modifyRadioButtonDrawable(mContext, rbDay, R.mipmap.list_scre_1x, 2);
                        day = true;
                    } else {
                        sort = "5";
                        Tools.modifyRadioButtonDrawable(mContext, rbDay, R.mipmap.list_scre_2x, 2);
                        day = false;
                    }
                    isRefresh = 0;
                    page = 1;
                    pageModel.homePageList(shop_id, class_id, sort, goods_date, p_id);
                }
                break;
            case R.id.rb_price:
                //按价格
                if (!isFastDoubleClick()) {
                    if (!price) {
                        sort = "6";
                        Tools.modifyRadioButtonDrawable(mContext, rbPrice, R.mipmap.list_scre_1x, 2);
                        price = true;
                    } else {
                        sort = "7";
                        Tools.modifyRadioButtonDrawable(mContext, rbPrice, R.mipmap.list_scre_2x, 2);
                        price = false;
                    }
                    isRefresh = 0;
                    page = 1;
                    pageModel.homePageList(shop_id, class_id, sort, goods_date, p_id);
                }
                break;
            case R.id.rb_period:
                //正期
                if (!isFastDoubleClick()) {
                    if (!isChecked) {
                        // 没有选中
                        goods_date = "1";
                        Tools.modifyRadioButtonDrawable(mContext, rbPeriod, R.mipmap.sf, 0);
                        isChecked = true;
                    } else {
                        Tools.modifyRadioButtonDrawable(mContext, rbPeriod, R.mipmap.s, 0);
                        goods_date = "";
                        isChecked = false;
                    }
                    isRefresh = 0;
                    page = 1;
                    pageModel.homePageList(shop_id, class_id, sort, goods_date, p_id);
                }
                break;
            case R.id.tv_follow:
                // 收藏
                showProgressDialog(getString(R.string.app_loading));
                collectModel = new CollectPresenter(this, mContext);
                collectModel.collect("2", shop_id, p_id);
                break;
            case R.id.tv_is_coup:
                if (isCheckedLogin()) {
                    bundle.putString("vids", vids);
                    intent.setClass(mContext, ExchangeActivity.class);
                    intent.putExtras(bundle);
                    startActivityForResult(intent, 200);
                } else {
                    startAct(LoginActivity.class);
                }
                break;
        }
    }

    @Override
    public void onCheckedChanged(RadioGroup radioGroup, int i) {
        switch (i) {
            case R.id.rb_tab1:
                buildIndicatorAnimatorTowards(rbTab1).start();
                tv_tag.setText("热卖排行");
                setVisibleGone(false);
                sort = "1";
                break;
            case R.id.rb_tab2:
                buildIndicatorAnimatorTowards(rbTab2).start();
                setVisibleGone(true);
                sort = "";
                break;
            case R.id.rb_tab3:
                sort = "8";
                buildIndicatorAnimatorTowards(rbTab3).start();
                tv_tag.setText("最新上传");
                setVisibleGone(false);
                break;
        }
        isRefresh = 0;
        page = 1;
        pageModel.homePageList(shop_id, class_id, sort, goods_date, p_id);
    }

    /**
     * 隐藏与显示
     *
     * @param isVG
     */
    private void setVisibleGone(boolean isVG) {
        if (isVG) {
            rgbs.setVisibility(View.VISIBLE);
            tvLine1.setVisibility(View.VISIBLE);
            tvLine2.setVisibility(View.VISIBLE);
            tv_tag.setVisibility(View.GONE);
        } else {
            rgbs.setVisibility(View.GONE);
            tvLine1.setVisibility(View.GONE);
            tvLine2.setVisibility(View.GONE);
            tv_tag.setVisibility(View.VISIBLE);
        }
    }

    /**
     * 选中tab页
     */
    private void initCheckedTab(final RadioButton rbTab) {
        rabs.post(new Runnable() {
            @Override
            public void run() {
                buildIndicatorAnimatorTowards(rbTab).start();
            }
        });
    }

    /**
     * 指示器动画
     *
     * @param tab
     * @return
     */
    private AnimatorSet buildIndicatorAnimatorTowards(TextView tab) {
        ObjectAnimator xAnimator = ObjectAnimator.ofFloat(indicator, "X", indicator.getX(), tab.getX());

        final ViewGroup.LayoutParams params = indicator.getLayoutParams();
        ValueAnimator widthAnimator = ValueAnimator.ofInt(params.width, tab.getMeasuredWidth());
        widthAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                params.width = (Integer) animation.getAnimatedValue();
                indicator.setLayoutParams(params);
            }
        });

        AnimatorSet set = new AnimatorSet();
        set.setInterpolator(new FastOutSlowInInterpolator());
        set.playTogether(xAnimator, widthAnimator);

        return set;
    }

    @Override
    public void onLoadMore() {
        //刷新
        isRefresh = 1;
        page++;
        if (!isNetworkConnected()) {
            adapter.pauseMore();
            return;
        }
        if (page > totalPage) {
            adapter.stopMore();
            return;
        }
        pageModel.homePageList(shop_id, class_id, sort, goods_date, p_id);
    }

    @Override
    public void shopHomePageSuccess(SearchGoods model) {
        if (model != null) {
            if (model.getStatus() == HttpUtil.RESULT_OK) {
                data = model.getData();
                totalPage = data.getTotalPage();
                // 下拉刷新 清空集合
                switch (isRefresh) {
                    case 0:
                        // 下拉刷新
                        list.clear();
                        list = model.getData().getModels();
                        break;
                    case 1:
                        // 上拉加载
                        list.addAll(model.getData().getModels());
                        break;
                }
                adapter.clear();
                adapter.addAll(list);
                adapter.notifyDataSetChanged();
                isCollect = data.getIs_collect();
                shop = data.getShop();
                SearchGoods.DataBean.ShopBean.VoucherInfo voucher_info = shop.getVoucher_info();
                if (voucher_info != null) {
                    vids = voucher_info.getVids();
                    existVoucher = voucher_info.getExist_voucher();
                    if (existVoucher == 1) {
                        tv_is_coup.setVisibility(View.VISIBLE);
                    } else {
                        tv_is_coup.setVisibility(View.GONE);
                    }
                }
                shop_name = shop.getShop_name();
                toChatUsername = shop.getShop_hx();
                shop_avatar = shop.getShop_avatar();
                mobile = shop.getPhone();

                score = shop.getScore();
                if (!Tools.isNull(shop_name)) {
                    tvShopName.setText(shop_name);
                } else {
                    tvShopName.setText("");
                }
                if (!Tools.isNull(shop_avatar)) {
                    Glide.with(mContext)
                            .load(HttpUtil.IMG_BASE_URL + shop_avatar)
                            .centerCrop()
                            .placeholder(R.mipmap.loading_4b3)
                            .diskCacheStrategy(DiskCacheStrategy.ALL)
                            .transform(new GlideCircleTransform(this))
                            .into(ivIcon);
                } else {
                    ivIcon.setImageResource(R.mipmap.loading_4b3);
                }
                // 是否收藏店铺
                switch (isCollect) {
                    case 0:
                        tv_follow.setText("收藏");
                        Tools.modifyTextViewDrawable(mContext, tv_follow, R.mipmap.guanzhu02_def_1x, 0);
                        break;
                    case 1:
                        tv_follow.setText("已收藏");
                        Tools.modifyTextViewDrawable(mContext, tv_follow, R.mipmap.guanzhu02_sel_1x, 0);
                        break;
                }
                ratingBar3.setCountSelected(score);

            } else {
                T.showToast(mContext, model.getMsg());
            }
        }
    }

    @Override
    public void collectSuccess(Collect model) {
        if (model != null) {
            if (model.getStatus() == HttpUtil.RESULT_OK) {
                String msg = model.getMsg();
                if (!Tools.isNull(msg) && msg.equals("收藏成功")) {
                    tv_follow.setText("已收藏");
                    Tools.modifyTextViewDrawable(mContext, tv_follow, R.mipmap.guanzhu02_sel_1x, 0);
                    if (data != null) {
                        data.setIs_collect(1);
                    }
                } else if (!Tools.isNull(msg) && msg.equals("取消成功")) {
                    tv_follow.setText("收藏");
                    Tools.modifyTextViewDrawable(mContext, tv_follow, R.mipmap.guanzhu02_def_1x, 0);
                    if (data != null) {
                        data.setIs_collect(0);
                    }
                }
                T.showToast(mContext, msg);
            } else {
                T.showToast(mContext, model.getMsg());
            }
        }
    }

    @Override
    public void getShopClassSuccess(ClassM model) {
        if (model != null) {
            if (model.getStatus() == HttpUtil.RESULT_OK) {
                values = model.getData();
            }
        }
    }

    @Override
    public void httpStatusError() {
        T.showToast(mContext, getString(R.string.app_http_error));
    }

    @Override
    public void hideLoading() {
        hideShowProgress();
    }


    /**
     * 选择保质期
     */
    public class PopupWindows extends PopupWindow {

        public PopupWindows(final Context mContext, View parent) {
            super(mContext);
            View view = View.inflate(mContext, R.layout.shop_type, null);
            final LinearLayout ll_popup = (LinearLayout) view.findViewById(R.id.ll_popup);
            RecyclerView recyclerView = (RecyclerView) view.findViewById(R.id.recyclerView);
            RelativeLayout rl_root = (RelativeLayout) view.findViewById(R.id.rl_root);
            LinearLayoutManager manager = new LinearLayoutManager(mContext);
            recyclerView.setItemAnimator(new DefaultItemAnimator());
            recyclerView.addItemDecoration(new RecycleViewDivider(
                    mContext, LinearLayoutManager.HORIZONTAL, Utils.dip2px(mContext, 0.5F), getResources().getColor(R.color.line_color)));
            recyclerView.setLayoutManager(manager);
            ShopTypeAdapter adapter = new ShopTypeAdapter(mContext);
            adapter.setList(values);
            recyclerView.setAdapter(adapter);
            adapter.setOnItemClickListener(new ShopTypeAdapter.OnItemClickListener() {
                @Override
                public void onItemClick(int position, View v) {
                    ClassM.DataBean bean = values.get(position);
                    Bundle bundle = new Bundle();
                    bundle.putString("shop_id", shop_id);
                    bundle.putString("cid", bean.getCid() + "");
                    startAct(ShopListActivity.class, bundle);
                    dismiss();
                }
            });
            final PopupWindow popupWindow = this;
            ll_popup.startAnimation(AnimationUtils.loadAnimation(mContext, R.anim.popshow_anim));
            rl_root.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    hidePopupWindows(ll_popup, popupWindow);
                }
            });
            setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
            setHeight(App.screenHeight - (ll_bottom.getHeight() + ToolbarUtil.getStatusBarHeight(mContext)));
            setBackgroundDrawable(new BitmapDrawable());
            setFocusable(true);
            setOutsideTouchable(true);
            setContentView(view);
            int[] location = new int[2];
            parent.getLocationOnScreen(location);
            showAtLocation(parent, Gravity.NO_GRAVITY, 0, 0);
            update();
        }

    }

    /**
     * 关闭 PopupWindows
     *
     * @param view
     * @param popupWindow
     */
    private void hidePopupWindows(View view, final PopupWindow popupWindow) {
        Animation animation = AnimationUtils.loadAnimation(mContext, R.anim.pophidden_anim);
        animation.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {

            }

            @Override
            public void onAnimationEnd(Animation animation) {
                popupWindow.dismiss();
            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });
        view.startAnimation(animation);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (registerReceiver != null) {
            unregisterReceiver(registerReceiver);
        }
    }


    public boolean Onrecord() {
        if (Build.VERSION.SDK_INT >= 23) {
            int checkCallPhonePermission = ContextCompat.checkSelfPermission(mContext, Manifest.permission.RECORD_AUDIO);
            if (checkCallPhonePermission != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(ShopHomeActivity.this, new String[]{Manifest.permission.RECORD_AUDIO}, 1);
                //Tools.callPhone(mobile,mContext);
                return false;
            } else {
                return true;
                //Tools.callPhone(mobile,mContext);
            }
        } else {
            return true;
            // Tools.callPhone(mobile,mContext);
        }
    }
}
